package com.dqhl.community.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.community.R;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.Community;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.view.BuildingSelectPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by guanluocang on 2016/9/4.
 * 补全信息
 */
public class ComplementInfoActivity extends BaseActivity implements View.OnClickListener {

    private Context context;
    private TextView tvCancel;
    private TextView tvTopTitle;
    private TextView tvConfirm;

    private TextView tvCommunity; //所在小区
    private TextView tvBuilding; //所在楼宇
    private TextView tvUnit; //所在单元
    private TextView tvHouse; //门牌号
    private EditText etTelephone; //手机号

    private String communityName; //所在小区名字
    private String communityId;  //所在小区id
    private String buildingName;
    private String buildingId; //楼宇id
    private String unitName;
    private String unitId;  //单元id
    private String houseName;
    private String houseId; //门牌号id
    private String userId; //用户id

    private List<Community> buildingList = new ArrayList<>(); // 楼宇list
    private BuildingSelectPopupWindow buildingSelectPopupWindow; // 楼宇选择
    private List<Community> unitList = new ArrayList<>(); //单元list
    private BuildingSelectPopupWindow unitSelectPopupWindow; // 单元选择
    private List<Community> houseList = new ArrayList<>(); //门牌号list
    private BuildingSelectPopupWindow houseSelectPopupWindow; // 门牌号选择

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complement_info);
        context = this;

        initData();
        initView();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        communityName = getIntent().getStringExtra("community_name");
        communityId = getIntent().getStringExtra("community_id");
        userId = getIntent().getStringExtra("user_id");
        Dlog.e("communityName:" + communityName + ";communityId" + communityId + ";userId:" + userId);

        getBuildingList(communityId);
    }

    /**
     * 根据小区id，获取楼宇list
     */
    private void getBuildingList(String id) {
        RequestParams params = new RequestParams(Config.Api.building);
        params.addBodyParameter("parent_id", id);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("result:" + result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 0) {
                    String data = JsonUtils.getInfo(result, "data");
                    buildingList = JSON.parseArray(data, Community.class);
                    Dlog.e("buildingList:" + buildingList);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 实例化数据
     */
    private void initView() {
        tvCancel = (TextView) findViewById(R.id.tv_cancel);
        tvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        tvTopTitle.setText(R.string.complement_info);
        tvConfirm = (TextView) findViewById(R.id.tv_confirm);

        tvCommunity = (TextView) findViewById(R.id.tv_community);
        tvCommunity.setText(communityName);
        tvBuilding = (TextView) findViewById(R.id.tv_building);
        tvUnit = (TextView) findViewById(R.id.tv_unit);
        tvHouse = (TextView) findViewById(R.id.tv_house);
        etTelephone = (EditText) findViewById(R.id.et_telephone);

        tvCancel.setOnClickListener(this);
        tvConfirm.setOnClickListener(this);
        tvBuilding.setOnClickListener(this);
        tvUnit.setOnClickListener(this);
        tvHouse.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel: //取消
                finish();
                break;
            case R.id.tv_confirm: //认证
                doConfirm();
                break;
            case R.id.tv_building:
                if (!buildingList.isEmpty() && buildingList.size() > 0) {
                    if (buildingSelectPopupWindow == null) {
                        buildingSelectPopupWindow = new BuildingSelectPopupWindow(ComplementInfoActivity.this, buildingList, buildingSelectListener);
                        buildingSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                buildingSelectPopupWindow.backgroundAlpha(1.0f);
                            }
                        });
                    }
                    buildingSelectPopupWindow.showAsDropDown(tvBuilding);
                }
                break;
            case R.id.tv_unit:
                if (!unitList.isEmpty() && unitList.size() > 0) {
                    unitSelectPopupWindow.showAsDropDown(tvUnit);
                } else {
                    toast("请先选择楼宇");
                }
                break;
            case R.id.tv_house:
                if (!houseList.isEmpty() && houseList.size() > 0) {
                    houseSelectPopupWindow.showAsDropDown(tvHouse);
                } else {
                    toast("请先选择单元");
                }
                break;
        }
    }

    AdapterView.OnItemClickListener buildingSelectListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            buildingId = buildingList.get(i).getId();
            buildingName = buildingList.get(i).getName();
            Dlog.e("选择了：" + buildingName);
            tvBuilding.setText(buildingName);
            buildingSelectPopupWindow.dismiss();
            getUnitList(buildingId);
        }
    };

    /**
     * 根据楼宇id 获取单元list
     *
     * @param id
     */
    private void getUnitList(String id) {
        RequestParams params = new RequestParams(Config.Api.unit);
        params.addBodyParameter("parent_id", id);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("result:" + result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 0) {
                    String data = JsonUtils.getInfo(result, "data");
                    unitList = JSON.parseArray(data, Community.class);
                    Dlog.e("unitList:" + unitList);
                    if (unitSelectPopupWindow == null) {
                        unitSelectPopupWindow = new BuildingSelectPopupWindow(ComplementInfoActivity.this, unitList, unitSelectListener);
                        unitSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                unitSelectPopupWindow.backgroundAlpha(1.0f);
                            }
                        });
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

    AdapterView.OnItemClickListener unitSelectListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            unitName = unitList.get(i).getName();
            unitId = unitList.get(i).getId();
            Dlog.e("选择了：" + unitName);
            tvUnit.setText(unitName);
            unitSelectPopupWindow.dismiss();
            getRoomList(unitId);
        }
    };

    /**
     * 根据单元id，获取门牌号list
     *
     * @param id
     */
    private void getRoomList(String id) {
        RequestParams params = new RequestParams(Config.Api.houseNumber);
        params.addBodyParameter("parent_id", id);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("result:" + result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 0) {
                    String data = JsonUtils.getInfo(result, "data");
                    houseList = JSON.parseArray(data, Community.class);
                    Dlog.e("houseList:" + houseList);
                    if (houseSelectPopupWindow == null) {
                        houseSelectPopupWindow = new BuildingSelectPopupWindow(ComplementInfoActivity.this, houseList, roomSelectListener);
                        houseSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                houseSelectPopupWindow.backgroundAlpha(1.0f);
                            }
                        });
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    AdapterView.OnItemClickListener roomSelectListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            houseName = houseList.get(i).getName();
            houseId = houseList.get(i).getId();
            Dlog.e("选择了：" + houseName);
            tvHouse.setText(houseName);
            houseSelectPopupWindow.dismiss();
        }
    };

    /**
     * 认证
     */
    private void doConfirm() {
        String mobilePhone = etTelephone.getText().toString();

        RequestParams params = new RequestParams(Config.Api.authentication);
        params.addBodyParameter("community_id", communityId);
        params.addBodyParameter("building_id", buildingId);
        params.addBodyParameter("unit_id", unitId);
        params.addBodyParameter("residence_id", houseId);
        params.addBodyParameter("userid", userId);
        params.addBodyParameter("mobile_phone", mobilePhone);
        Dlog.e(communityId + ";" + buildingId + ";" + unitId + ";" + houseId + ";" + userId + ";" + mobilePhone);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getInfo(result, "errMsg");
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    // 认证成功，发送一个广播
                    Intent intent = new Intent(Constant.ACTION_COMPLAIN);
                    intent.putExtra(Constant.COMMUNITY_NAME, communityName);
                    sendBroadcast(intent);

                    String authentication = JsonUtils.getInfo(data, "authentication");

                    //将认证状态保存起来
                    app.setAuthentication(authentication);
                    spUserInfo.edit().putString(Constant.AUTHENTICATION, authentication).apply();
                    String address = communityName + buildingName + unitName + houseName;
                    spUserInfo.edit().putString(Constant.ADDRESS, address).apply();

                    toast("认证成功");
                    finish();
                } else {
                    Dlog.e("认证失败：" + errMsg);
                    toast("认证失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
